package com.yanx.system.base.domain.manager;

import com.yanx.common.core.domain.manager.BaseManager;
import com.yanx.system.base.domain.entity.SysConfig;
import com.yanx.system.base.domain.repository.SysConfigRepository;
import com.yanx.system.web.infra.cache.SysConfigCache;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

/**
 * 参数配置领域服务
 *
 * @author: gotanks
 * @create: 2023-6-2
 */
@Service
public class SysConfigManager extends BaseManager<SysConfig, SysConfigRepository> {

    /**
     * 项目启动时，初始化参数到缓存
     */
    @PostConstruct
    public void init() {
        loadingConfigCache();
    }

    public boolean checkConfigKeyUnique(String configKey) {
        int num = repository.countByConfigKey(configKey);
        return num > 0;
    }

    public boolean checkConfigKeyUnique(String configKey, Long id) {
        int num = repository.countByConfigKeyAndIdNot(configKey, id);
        return num > 0;
    }

    public void resetConfigCache() {
        clearConfigCache();
        loadingConfigCache();
    }

    private void loadingConfigCache() {
        SysConfigCache.INSTANCE.loadingAll();
    }

    private void clearConfigCache() {
        SysConfigCache.INSTANCE.deleteAll();
    }

}
